<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" v-on:change="changeKeyword" placeholder="角色名称/标识"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="searchRole">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
<!--			<el-table-column prop="id" label="姓名" width="80" sortable>-->
<!--			</el-table-column>-->
			<el-table-column prop="name" label="角色名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="标识" width="120" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="warning" size="small" @click="handleRole(scope.$index, scope.row)">设置权限</el-button>
					<el-button type="primary" size="small" @click="handleMenu(scope.$index, scope.row)">设置菜单</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="20"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--设置权限界面-->
    <el-dialog title="权限设置" :visible.sync="setPermissionVisible" :close-on-click-modal="false">
      <el-form :model="rolePermission" label-width="80px" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in permissionTree" :key="p.sn">
          <template>
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='rolePermission.permissionSns' :label="p.sn"
                         @change='handleCheck(1,indexkey)'>
              {{p.name}}
            </el-checkbox>
            <div style="margin-bottom: 20px;">
              <div v-for="c in p.children" class="line-check" :key="c.sn"
                   style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                <el-checkbox class="check2" @change='handleCheck(2,indexkey)'
                             v-model="rolePermission.permissionSns" :label="c.sn">
                  {{c.name}}
                </el-checkbox>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setPermissionVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRolePermission" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

		<!--新增/修改界面-->
		<el-dialog title="新增角色" :visible.sync="addRoleVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="角色名称" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="标识">
					<el-input v-model="addForm.sn"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addRoleVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
					name: ''
				},
				listLoading: false,
				sels: [],//列表选中列
        pageInfo: {
          total: 0,
          rows: []
        },
        query: {
          currentPage: 1,	// 当前页，默认第一页
          pageSize : 10,// 每页展示数据，默认10条
          keyword: ""// 关键字-查询条件
        },
        // 权限设置弹出框
        setPermissionVisible: false,
        // 全选按钮
        isIndeterminate: false,
        checkAll: false,
        // 提交加载框
        saveLoading: false,
        // 权限树
        permissionTree: [],
        // 为角色添加权限的双向绑定
        rolePermission: {
          roleId: null,
          permissionSns: []
        },
        allPermissionSns: [],

        addRoleVisible: false,// 新增/编辑界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入角色名称', trigger: 'blur' }
					]
				},
				// 新增/编辑界面数据
				addForm: {
					name: '',
					sn: ''
				}
			}
		},
		methods: {
      // 数组角色菜单
      handleMenu() {

      },
      // 设置权限按钮
      handleRole(index,row) {
        // 获取权限树
        this.getPermissionTree();
        this.setPermissionVisible = true
        // 将当前数据的id值赋值给roleId
        this.rolePermission.roleId = row.id;
        // 获取当前角色的权限
        this.getRolePermission(row.id);

      },
			handleCurrentChange(val) {
				this.page = val;
				this.getRoles();
			},
      // 高级查询
      changeKeyword() {
        this.searchRole();
      },
      searchRole() {
        this.query.currentPage = 1;
        this.getRoles();
      },
			//获取角色列表
			getRoles() {
        this.$http.post("/role",this.query)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.pageInfo = result.data;
            } else {
              this.$message({message:result.message, type: 'success'});
            }
          })
          .catch(result => {
            this.$message({message:"网络错误："+result, type: 'success'});
          })
			},
			//删除
			handleDel(index, row) {
				this.$confirm('确认删除该角色吗?同时也会删除角色所有权限', '提示', {type: 'warning'})
          .then(() => {
            this.$http.delete("/role/"+row.id)
              .then(result => {
                result = result.data;
                if (result.success) {
                  this.$message({message: result.message, type: 'success'})
                } else {
                  this.$message({message:result.message, type: 'success'});
                }
                this.getRoles();
              })
              .catch(result => {
                this.$message({message:"网络错误："+result, type: 'success'});
              })
          })
          .catch(() => {
            this.$message({message:"你取消了删除：", type: 'warning'});
          });
			},
			//显示新增/编辑界面
			handleAdd() {
				this.addRoleVisible = true;
				this.addForm = {
					name: '',
					sn: ''
				};
			},
			// 新增/编辑角色
			addSubmit() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {})
              .then(() => {
                this.addLoading = true;
                let para = Object.assign({}, this.addForm);
                this.$http.put("/role",para)
                  .then(result => {
                    result = result.data;
                    if (result.success) {
                      this.addLoading = false;
                      this.$message({message:result.message, type: 'success'});
                    } else {
                      this.$message({message:result.message, type: 'error'})
                    }
                    this.getRoles();
                    this.addRoleVisible = false;
                  })
                  .catch(result => {
                    this.$message({message:"网络错误："+result, type: 'success'});
                  })
						  })
					}
				});
			},
      // 全选框
			selsChange(sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove() {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？该操作同样会删除对应角色的所有权限', '提示', {type: 'warning'})
          .then(() => {
            this.listLoading = true;
            let para = { ids: ids };
            this.$http.patch("/role",para)
              .then(result => {
                result = result.data;
                if (result.success) {
                  this.$message({message: result.message, type: 'success'})
                } else {
                  this.$message({message: result.message, type: 'error'})
                }
              })
              .catch(result => {
                this.$message({message: "错误："+result.message, type: 'error'})
              })
				  })
          .catch(() => {
            this.$message({message: "你取消了批量删除！", type: 'warning'})
				  });
			},
      // 根据id获取角色权限
      getRolePermission(id) {
        this.$http.get("/role/getRolePer/"+id)
          .then(result => {
            result = result.data;
            if (result.success) {
              // 获取到对应角色的权限，并将当前角色权限赋值给this.rolePermission.permissionSns
              this.rolePermission.permissionSns = result.data;
              // 处理全选按钮
              // 获取已选中的长度
              let checkedCount = this.rolePermission.permissionSns.length;
              // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
              this.checkAll = checkedCount === this.allPermissionSns.length;
              console.log(checkedCount,this.allPermissionSns.length)
              // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
              this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
            } else {
              this.$message({message: result.message, type: 'error'})
            }
          })
          .catch(result =>{
            this.$message({message: "错误："+result.message, type: 'error'})
          })
      },

      // 权限提交保存按钮
      saveRolePermission() {
        console.log("权限提交：",this.rolePermission)
        this.$http.post("/role/saveRolePer",this.rolePermission)
          .then(result => {
            result = result.data;
            if(result.success){
              this.$message({ message: '设置权限成功：'+result.message,type: 'success'});
              this.setPermissionVisible = false;
            }else{
              this.$message({ message: result.message,type: 'error'});
            }
          })
          .catch(result => {
            this.$message({ message: '系统错误:'+result,type: 'error'});
          })
      },
      // 获取权限树
      getPermissionTree() {
        this.allPermissionSns = [];
        this.$http.get("/permission/tree")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.permissionTree = result.data
              for (let i = 0; i < this.permissionTree.length; i++) {
                let p = this.permissionTree[i];
                this.allPermissionSns.push(p.sn);
                let c = p.children
                if (c) {
                  for (let j = 0; j < c.length; j++) {
                    this.allPermissionSns.push(c[j].sn);
                  }
                }
              }
              console.log("权限数组的长度",this.allPermissionSns.length)
            } else {
              this.$message({message: result.message, type: 'error'})
            }
          })
          .catch(result => {
            this.$message({message: "网络错误："+result, type: 'error'})
          })
      },

      // 全选按钮
      handleCheckAllChange(val){
        this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
        this.isIndeterminate = false;
      },
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
      handleCheck(type, a = 0) { // 多选框
        // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
        let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
        if (type == 2) { // 二级菜单点击
          let index = 0;  //
          this.permissionTree[a].children.map(item => {
            // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
            if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
              index += 1;
            }
          })
          if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
            if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
              this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
            }
          } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
            if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
              this.rolePermission.permissionSns.splice(indexOf, 1);
            }
          }
        } else {  // 一级菜单点击
          if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) < 0) {
                this.rolePermission.permissionSns.push(item.sn)
              }
            })
          } else {
            // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) > -1) {
                this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n == item.sn), 1);
              }
            })
          }
        }
        // 获取已选中的长度
        let checkedCount = this.rolePermission.permissionSns.length;
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allPermissionSns.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
      },
		},
		mounted() {
			this.getRoles();
		}
	}

</script>

<style scoped>

</style>